package com.example.springboot.config.intercepors;


import com.example.springboot.domain.Admin;
import com.example.springboot.domain.User;
import com.example.springboot.utils.JwtUtil;
import com.example.springboot.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    RedisTemplate redisTemplate;

    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的Session提取来验证登陆。
//        HttpSession session = request.getSession();
//        //这里是登陆时放入session的
//
//        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        Claims tokenBody=null;
        Admin admin=new Admin();
        Boolean flag = false;
        String authorization = request.getHeader("Authorization");

        if (authorization != null && !authorization.isEmpty()) {
            String token = authorization.split(" ")[1];
             admin= JwtUtil.getAdmin(token);
        }

//        /**
//         * 使用token验证角色
//         */
//        String json = (String) redisTemplate.opsForValue().get(admin.getRoleId());
//        //Json转化为对象实例
//        json = json.substring(1,json.length()-1);
//        String[] split = json.split(",");


        String requestURI = request.getRequestURI();
        //从redis取出菜单地址，设置拦截器
        // 如果是登录接口，让其通过
        if (requestURI.equals("/user/login")) {
            return true;
        }
        if (admin.getUsername() == null ){
            log.warn("token为空");
            response.sendRedirect("/user/loginFail");
            return false;
        }
//        if(requestURI.contains("page/")){
//            for (String s : split) {
//                if(requestURI.contains(s)){
//                    flag = true;
//                }
//            }
//            return flag;
//        }


        ThreadLocalUtil.set(admin);
        return true;    //表示该用户发送其他请求数据



    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
